#! /usr/bin/env python
# -*- coding:utf-8 -*-

import urllib.request
import urllib.parse
import json
import hashlib
import time


class YoudaoFanyi(object):
    def __init__(self):
        self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

        self.header = {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie": "OUTFOX_SEARCH_USER_ID=951491520@10.108.160.17; JSESSIONID=aaajVyhlHEQEpfA_STqXw; OUTFOX_SEARCH_USER_ID_NCOO=1342654615.1026268; ___rl__test__cookies=1564722262675",
            "Host": "fanyi.youdao.com",
            "Origin": "http://fanyi.youdao.com",
            "Referer": "http://fanyi.youdao.com/",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
        }

        self.data = {
            "i": "",  # 待翻译字符串
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": "",  # 待补充的token
            "sign": "",
            "ts": "",
            "bv": "5aa27179d067b879dc648ca75f375799",
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTlME"
        }

    def token(self, q):
        ts = str(int(time.time() * 1000))
        salt = ts + '0'  # 手动随机数，美滋滋
        composed_str = 'fanyideskweb' + q + salt + 'n%A-rKaT5fb[Gy?;N5@Tj'
        sign = hashlib.md5(composed_str.encode('utf-8')).hexdigest()
        return ts, salt, sign


    def query(self, q):
        self.data['i'] = q  # 填入待查询字符串
        self.data['ts'], self.data['salt'], self.data['sign'] = self.token(q)

        formdata = urllib.parse.urlencode(self.data).encode('utf-8')
        req = urllib.request.Request(url=self.url, data=formdata, headers=self.header)
        response = json.loads(urllib.request.urlopen(req).read().decode("utf-8"))
        print(response['translateResult'][0][0]['tgt'])


if __name__ == '__main__':
    fanyi = YoudaoFanyi()
    while True:
        q = input("请输入您想要翻译的内容(直接回车退出程序)：")
        if q:
            fanyi.query(q)
        else:
            print("程序退出！")
            break